<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10">
        <div class="main_ti box">
          <el-tabs v-model="activeName" @tab-click="handleClick" class="box">
            <el-tab-pane label="商品损耗" name="1"></el-tab-pane>
            <el-tab-pane label="采购员/供应商损耗" name="2"></el-tab-pane>
          </el-tabs>
        </div>

        <div
          class="mainor_form batch-wrap"
          v-show="activeName == 1"
          style="margin-top: 16px"
        >
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="90px"
            id="form"
          >
            <el-form-item label="入库日期：" prop="establishTime">
              <el-date-picker
                v-model="establishTime"
                type="daterange"
                class="time220"
                :editable="false"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :clearable="false"
                :picker-options="pickerOptions"
                @change="(val) => dateChange(val, 1)"
              />
            </el-form-item>

            <el-form-item
              label="商品名称："
              prop="goods_spu_id"
              v-if="activeName == 1"
            >
              <change-goods-input
                ref="changeGoodsInput"
                @clear="
                  () => {
                    this.form.goods_spu_id = '';
                  }
                "
                @sendValue="
                  (data) => {
                    this.form.goods_spu_id = data.id;
                  }
                "
              ></change-goods-input>
            </el-form-item>
            <el-form-item
              v-show="activeName == 1"
              label="商品分类："
              prop="category_id"
              class="wid220"
            >
              <el-cascader
                v-model="form.category_id"
                :options="options"
                :props="defaultProps"
                ref="cascaderHandle"
                @change="getArticleList"
              ></el-cascader>
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="false">
              <el-button @click="exportform">导出</el-button>
            </MainFormBtn>
          </el-form>
        </div>

        <div
          class="mainor_form batch-wrap"
          v-show="activeName == 2"
          style="margin-top: 16px"
        >
          <div class="mainor_te"></div>
          <el-form
            :inline="true"
            :model="form_user"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="90px"
          >
            <el-form-item label="配送日期：" prop="establishTime_user">
              <el-date-picker
                v-model="establishTime_user"
                type="daterange"
                class="time220"
                :editable="false"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :clearable="false"
                :picker-options="pickerOptions"
                @change="(val) => dateChange(val, 2)"
              />
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getArticleList" :loading="listLoading_user" :showBtn="false">
              <el-button @click="exportform">导出</el-button>
            </MainFormBtn>
          </el-form>
        </div>

        <div v-if="activeName == 1" v-cloak>
          <div class="main_table mg-t-6">
            <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list"
            element-loading-text="加载中"
            fit
            highlight-current-row
            :header-cell-class-name="this.$verticaline"
            :height="borderHeight"
            :header-cell-style="tableHeightStyle"
          >
            <el-table-column
              label="商品名称"
              prop="goods_name"
              min-width="110"
              show-overflow-tooltip
            >
              <template slot-scope="scope">{{ scope.row.goods_name }}</template>
            </el-table-column>
            <el-table-column
              label="商品分类"
              prop="category"
              min-width="110"
              show-overflow-tooltip
            />
            <el-table-column
              label="SKU编码"
              prop="goods_spu_code"
              min-width="110"
              show-overflow-tooltip
            />

            <el-table-column label="单位" prop="unit" show-overflow-tooltip />
            <el-table-column
              label="应入库数量"
              prop="num"
              min-width="110"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              label="实入库数量"
              prop="storage_num"
              min-width="110"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              label="损耗金额"
              prop="ullage_money"
              min-width="110"
              show-overflow-tooltip
            >
              <template slot="header">
                <headerSortArrow
                  label="ullage_money"
                  ref="arrow1"
                  @handleSort="handleSort($event, 'arrow1')"
                  >损耗金额</headerSortArrow
                >
              </template>
              <template slot-scope="scope">
                <div>
                  {{ scope.row.ullage_money | twoPlace }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="损耗数量"
              prop="ullage_num"
              min-width="110"
              show-overflow-tooltip
            >
              <template slot="header">
                <headerSortArrow
                  label="ullage_num"
                  ref="arrow2"
                  @handleSort="handleSort($event, 'arrow2')"
                  >损耗数量</headerSortArrow
                >
              </template>
            </el-table-column>
            <el-table-column
              label="损耗率"
              prop="rate"
              min-width="110"
              show-overflow-tooltip
            >
              <template slot="header">
                <headerSortArrow
                  label="rate"
                  ref="arrow3"
                  @handleSort="handleSort($event, 'arrow3')"
                  >损耗率</headerSortArrow
                >
              </template>
              <template slot-scope="scope"
                >{{ scope.row.ullage_rate }}%</template
              >
            </el-table-column>
            <el-table-column
              label="管理操作"
              prop="rate"
              width="120"
              align="center"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-link type="primary" @click="handleDetail(scope.row, 1)">
                  明细
                </el-link>
              </template>
            </el-table-column>
            </el-table>
          </div>
          <div class="main_page boxdq">
            <div></div>
            <!-- 分页 -->
            <div class="main_page_r">
              <MainPagination
                :current-page="current.page"
                :page-sizes="[20, 30, 50, 100]"
                :page-size="limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalCount"
                background
                @size-change="changeLimit"
                @current-change="changePage"
              />
            </div>
          </div>
        </div>

        <div v-if="activeName == 2" v-cloak>
          <div class="main_table mg-t-6">
            <el-table
            ref="multipleTable"
            v-loading="listLoading_user"
            :data="list_user"
            element-loading-text="加载中"
            fit
            highlight-current-row
            :default-sort="{ prop: 'rate' }"
            :header-cell-class-name="this.$verticaline"
            :height="borderHeight"
            :header-cell-style="tableHeightStyle"
          >
            <el-table-column label="采购员/供应商" prop="supplier_or_buyer">
              <template slot-scope="scope">{{
                scope.row.supplier_or_buyer
              }}</template>
            </el-table-column>

            <el-table-column label="损耗金额" prop="money">
              <template slot="header">
                <headerSortArrow
                  label="money"
                  ref="arrow5"
                  @handleSort="handleSort($event, 'arrow5')"
                  >损耗金额</headerSortArrow
                >
              </template>
              <template slot-scope="scope">
                {{ scope.row.ullage_money | twoPlace }}
              </template>
            </el-table-column>
            <el-table-column label="损耗率" prop="rate">
              <template slot="header">
                <headerSortArrow
                  label="rate"
                  ref="arrow6"
                  @handleSort="handleSort($event, 'arrow6')"
                  >损耗率</headerSortArrow
                >
              </template>
              <template slot-scope="scope"
                >{{ scope.row.ullage_rate }}%</template
              ></el-table-column
            >
            <el-table-column
              label="管理操作"
              prop="rate"
              width="120"
              align="center"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-link type="primary" @click="handleDetail(scope.row, 2)">
                  明细
                </el-link>
              </template>
            </el-table-column>
            </el-table>
          </div>
          <div class="main_page boxdq">
            <div></div>
            <!-- 分页 -->
            <div class="main_page_r">
              <MainPagination
                :current-page="current_user.page"
                :page-sizes="[20, 30, 50, 100]"
                :page-size="limit_user"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalCount_user"
                background
                @size-change="changeLimit"
                @current-change="changePage"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 每日明细 -->
    <el-drawer
      class="report_drawer drawer_min900"
      title="每日明细"
      size="50%"
      :visible.sync="goods_drawer"
      direction="rtl"
    >
      <div class="drawer_container">
        <div class="drawer_container_header">
          <div class="heder_left">
            <span>{{ drawer_title }}</span>
          </div>
          <div class="header_right">
            <el-button type="primary" @click="exportdetail">导出</el-button>
          </div>
        </div>
        <div class="drawer_container_main">
          <div class="main_table marginTop10" style="min-height: 400px">
            <el-table
              ref="multipleTable"
              v-loading="drawer_loading"
              :data="drawer_list"
              element-loading-text="加载中"
              fit
              border
              highlight-current-row
              :header-cell-class-name="this.$verticaline"
            >
              <el-table-column label="入库日期" prop="date">
                <template slot-scope="scope">{{ scope.row.date }}</template>
              </el-table-column>
              <el-table-column
                label="采购员/供应商"
                v-if="drawer_type == 1"
                prop="name"
              />

              <el-table-column label="损耗数量" prop="ullage_num">
              </el-table-column>
              <el-table-column label="损耗金额" prop="ullage_money">
                <template slot-scope="scope">
                  {{ scope.row.ullage_money | twoPlace }}
                </template>
              </el-table-column>
              <el-table-column label="损耗率" prop="ullage_rate">
                <template slot-scope="scope">
                  {{ scope.row.ullage_rate }}%
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="main_page boxdq">
            <div></div>
            <!-- 分页 -->
            <div class="main_page_r">
              <MainPagination
                :current-page="drawer_current.page"
                :page-sizes="[20, 30, 50, 100]"
                :page-size="drawer_limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="drawer_totalCount"
                background
                @size-change="changeLimit_drawer"
                @current-change="changePage_drawer"
              />
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import {
  get_ullagepurchase,
  get_ullagebuyerandsupplier,
  export_exportullagepurchase,
  export_exportullagebuyerandsupplier,
  get_ullagePurchaseDetail,
  export_exportUllagePurchaseDetail,
  get_ullageBuyerAndSupplierDay,
  export_exportUllageBuyerAndSupplierDay,
} from "@/api/report/index";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { report_shortcuts } from "@/options/new_dateOption";
import { parseTime, exportMethod, getNowMonth } from "@/utils/index";
import { recursion, category } from "@/utils/index";
import headerSortArrow from "@/views/report/components/headerSortArrow";

export default {
  mixins: [mixins],
  components: { headerSortArrow },
  data() {
    return {
      pickerOptions: report_shortcuts,
      exportMethod,
      getNowMonth,
      // 时间
      parseTime,
      // 商品
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      list: [],
      listLoading: false,
      form: {
        start_time: "",
        end_time: "",
        pid: "",
        category_id: "",
        goods_spu_id: "",
        order_by: "",
        order_type: "", //1升序  2降序
      },
      // 分类
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        checkStrictly: true,
      },
      options: [],
      establishTime: [],
      // 采购员
      current_user: {
        page: 1,
        per_page: 20,
      },
      limit_user: 20,
      totalCount_user: 1,
      list_user: [],
      listLoading_user: false,
      form_user: {
        start_time: "",
        end_time: "",
        order_by: "",
        order_type: "", //1升序  2降序
      },
      establishTime_user: [],
      activeName: "1",
      // 侧滑
      drawer_title: "",
      goods_drawer: false,
      drawer_list: [],
      drawer_loading: false,
      // 分页
      drawer_current: {
        page: 1,
        per_page: 20,
      },
      drawer_limit: 20,
      drawer_totalCount: 1,
      drawer_form: {
        start_time: "",
        end_time: "",
      },
      drawer_type: 1,
    };
  },
  created() {
    // 列表
    this.getNumerical(285);
    this.establishTime = this.getNowMonth();
    this.establishTime_user = this.getNowMonth();
    this.get_ullagepurchase();
  },
  methods: {
    startGetting() {
      this.getArticleList();
    },
    get_ullagepurchase() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      get_ullagepurchase(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.list = res.data.list;
          this.totalCount = res.data.total;
          this.options = recursion(res.data.categoryList, true);
        }
      });
    },
    get_ullagebuyerandsupplier() {
      this.listLoading_user = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form_user(),
        this.current_user
      );
      get_ullagebuyerandsupplier(data).then((res) => {
        this.listLoading_user = false;
        if (res.errcode == 0) {
          this.list_user = res.data.list;
          this.totalCount_user = res.data.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 重置
    reset() {
      if (this.activeName == 1) {
        this.$refs["userListFrom"].resetFields();
        this.establishTime = this.getNowMonth();
        this.$refs["changeGoodsInput"].name = "";
        this.form.goods_spu_id = "";
        this.getArticleList();
      } else if (this.activeName == 2) {
        this.$refs["userListFrom"].resetFields();
        this.establishTime = this.getNowMonth();
        this.getArticleList();
      }
    },
    // 搜索
    getArticleList() {
      if (this.activeName == 1) {
        this.current.page = 1;
        this.get_ullagepurchase();
      } else if (this.activeName == 2) {
        this.current_user.page = 1;
        this.get_ullagebuyerandsupplier();
      }
    },
    // 分页
    changeLimit(pageSize) {
      if (this.activeName == 1) {
        this.current.per_page = pageSize;
        this.get_ullagepurchase();
      } else if (this.activeName == 2) {
        this.current_user.per_page = pageSize;
        this.get_ullagebuyerandsupplier();
      }
    },
    changePage(page) {
      if (this.activeName == 1) {
        this.current.page = page;
        this.get_ullagepurchase();
      } else if (this.activeName == 2) {
        this.current_user.page = page;
        this.get_ullagebuyerandsupplier();
      }
    },
    changeLimit_drawer(pageSize) {
      this.drawer_current.per_page = pageSize;
      if (this.drawer_type == 1) {
        this.get_ullagePurchaseDetail();
      } else if (this.drawer_type == 2) {
        this.get_ullageBuyerAndSupplierDay();
      }
    },
    changePage_drawer(page) {
      this.drawer_current.page = page;
      if (this.drawer_type == 1) {
        this.get_ullagePurchaseDetail();
      } else if (this.drawer_type == 2) {
        this.get_ullageBuyerAndSupplierDay();
      }
    },

    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.start_time = this.establishTime[0] ? this.establishTime[0] : "";
      form.end_time = this.establishTime[1] ? this.establishTime[1] : "";
      form.pid = form.category_id[0] ? form.category_id[0] : "";
      form.category_id = category(form.category_id);
      return form;
    },
    list_form_user() {
      let form = JSON.parse(JSON.stringify(this.form_user));
      form.start_time = this.establishTime_user[0]
        ? this.establishTime_user[0]
        : "";
      form.end_time = this.establishTime_user[1]
        ? this.establishTime_user[1]
        : "";

      return form;
    },
    // 排序
    handleSort(data, ref) {
      switch (this.activeName) {
        case "1":
          let arr = ["arrow1", "arrow2", "arrow3"].filter((e) => e != ref);
          arr.map((e) => {
            this.$refs[e].selected = false;
          });
          this.form.order_by = data.label;
          this.form.order_type = data.type;
          this.get_ullagepurchase();
          break;
        case "2":
          let cc = ["arrow5", "arrow6"].filter((e) => e != ref);
          cc.map((e) => {
            this.$refs[e].selected = false;
          });
          this.form_user.order_by = data.label;
          this.form_user.order_type = data.type;
          this.get_ullagebuyerandsupplier();
          break;
      }
    },
    handleClick(tab, event) {
      if (this.activeName == 1) {
        this.current.page = 1;
        this.get_ullagepurchase();
      } else if (this.activeName == 2) {
        this.current.page = 1;
        this.get_ullagebuyerandsupplier();
      }
    },
    // 列表导出
    exportform() {
      if (this.activeName == 1) {
        this.export_exportullagepurchase();
      } else if (this.activeName == 2) {
        this.export_exportullagebuyerandsupplier();
      }
    },
    // 明细导出
    exportdetail() {
      switch (this.drawer_type) {
        case 1:
          this.export_exportUllagePurchaseDetail();
          break;

        case 2:
          this.export_exportUllageBuyerAndSupplierDay();
          break;
      }
    },
    //商品导出
    export_exportullagepurchase() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_exportullagepurchase(data).then((res) => {
        this.exportMethod(res, "采购商品损耗", notify);
      });
    },
    // 采购员
    export_exportullagebuyerandsupplier() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form_user(),
        this.current_user
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_exportullagebuyerandsupplier(data).then((res) => {
        this.exportMethod(res, "采购员/供应商损耗", notify);
      });
    },
    // 每日明细导出
    export_exportUllageBuyerAndSupplierDay() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.drawer_form,
        this.drawer_current
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_exportUllageBuyerAndSupplierDay(data).then((res) => {
        this.exportMethod(res, "每日明细", notify);
      });
    },
    // 商品每日明细导出
    export_exportUllagePurchaseDetail() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.drawer_form,
        this.drawer_current
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_exportUllagePurchaseDetail(data).then((res) => {
        this.exportMethod(res, "商品损耗每日明细", notify);
      });
    },
    dateChange(val, type) {
      let start = new Date(val[0]).getTime();
      let end = new Date(val[1]).getTime();
      let diff = start - end;
      if (Math.abs(diff) > 3600 * 1000 * 24 * 60) {
        this.$message.warning("选择时间跨度不能超过两个月");
        this.establishTime = this.getNowMonth();
        this.establishTime_user = this.getNowMonth();
      }
      switch (type) {
        case 1:
          this.get_ullagepurchase();
          break;
        case 2:
          this.get_ullagebuyerandsupplier();
          break;
      }
    },
    // 明细
    handleDetail(row, type) {
      this.drawer_type = type;
      this.drawer_current.page = 1;
      this.drawer_current.per_page = 20;
      switch (type) {
        case 1:
          this.drawer_title = row.goods_name;
          let form = {
            start_time: "",
            end_time: "",
            goods_spu_id: row.goods_spu_id,
          };
          if (this.establishTime) {
            form.start_time = this.establishTime[0]
              ? this.establishTime[0]
              : "";
            form.end_time = this.establishTime[1] ? this.establishTime[1] : "";
          }
          this.drawer_form = form;
          this.get_ullagePurchaseDetail();
          break;
        case 2:
          this.drawer_title = row.supplier_or_buyer;
          let form2 = {
            start_time: "",
            end_time: "",
            buyer_id: row.buyer_id,
            supplier_id: row.supplier_id,
          };
          if (this.establishTime_user) {
            form2.start_time = this.establishTime_user[0]
              ? this.establishTime_user[0]
              : "";
            form2.end_time = this.establishTime_user[1]
              ? this.establishTime_user[1]
              : "";
          }
          this.drawer_form = form2;
          this.get_ullageBuyerAndSupplierDay();
          break;
      }
      this.goods_drawer = true;
    },
    // 采购员
    get_ullageBuyerAndSupplierDay() {
      this.drawer_loading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.drawer_form,
        this.drawer_current
      );
      get_ullageBuyerAndSupplierDay(data).then((res) => {
        if (res.errcode == 0) {
          this.drawer_loading = false;
          this.drawer_list = res.data.list;
          this.drawer_totalCount = res.data.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 商品明细
    get_ullagePurchaseDetail() {
      this.drawer_loading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.drawer_form,
        this.drawer_current
      );
      get_ullagePurchaseDetail(data).then((res) => {
        if (res.errcode == 0) {
          this.drawer_loading = false;
          this.drawer_list = res.data.list;
          this.drawer_totalCount = res.data.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: calc(100% - 280px);
  }
}

// 支付状态
.main_ti {
  display: flex;
  align-items: center;
  flex-direction: row;
  margin-bottom: 15px;
  padding-bottom: 1px;
  position: relative;
  .back {
    padding: 0 55px 0 0;
    font-size: 14px;
    color: #03a98e;
    display: flex;
    align-items: center;
    flex-direction: row;
    font-size: 0;
    a {
      font-size: 14px;
      color: #03a98e;
    }
    span {
      font-size: 14px;
      padding: 0 14px;
      transform: translateY(-1px);
    }
  }
  /deep/.el-tabs__header {
    margin: 0;
  }
  /deep/.el-checkbox {
    margin-top: 12px;
  }
  &::after {
    height: 1px;
    content: "";
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    background-color: #e4e7ed;
    z-index: 1;
  }
  /deep/.el-tabs__nav-wrap::after {
    height: 0;
  }
}
/deep/ .el-form-item--small.el-form-item {
  margin-bottom: 10px;
}
</style>
